<template>
  <div ref="tablebox" style="max-height: 100%; height: 100%; overflow: auto">
    <el-table :data="tableData()" :height="tableHeight" stripe style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="date" label="Date" min-width="100" sortable />
      <el-table-column prop="name" label="Name" sortable />
      <el-table-column prop="address" label="Address" sortable />
    </el-table>
    <div ref="paginationbox">
      <el-pagination
        class="container"
        background
        layout="prev, pager, next,total ,sizes,jumper"
        :total="state.total"
        :pager-count="5"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElTable, ElTableColumn, ElPagination } from 'element-plus'
import { onMounted, onUnmounted, reactive, ref, useTemplateRef } from 'vue'

const allTableData = [
  { date: '2016-05-02', name: '王小明', address: '上海市普陀区金沙江路 1518 弄' },
  { date: '2016-05-04', name: '王小红', address: '上海市普陀区金沙江路 1518 弄' },
  { date: '2016-05-01', name: '王小刚', address: '上海市普陀区金沙江路 1518 弄' },
  { date: '2016-05-03', name: '王小亮', address: '上海市普陀区金沙江路 1518 弄' },
]

//表格用到的参数
const state = reactive({
  page: 1,
  limit: 10,
  total: allTableData.length,
})
//前端限制分页（tableData为当前展示页表格）
function tableData() {
  return allTableData.filter(
    (item, index) => index < state.page * state.limit && index >= state.limit * (state.page - 1),
  )
}
//改变页码
function handleCurrentChange(e: number) {
  state.page = e
}
//改变页数限制
function handleSizeChange(e: number) {
  state.limit = e
}

// table自适应高度
const tableHeight = ref(0)
const tablebox = useTemplateRef('tablebox')
const paginationbox = useTemplateRef('paginationbox')

function setTableHeight() {
  if (tablebox.value && paginationbox.value) {
    tableHeight.value =
      tablebox.value.getBoundingClientRect().height -
      paginationbox.value.getBoundingClientRect().height
  }
}

// 防抖和节流
function debounce(fn: () => void, delay: number) {
  let timer: number
  return function () {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn()
    }, delay)
  }
}

const setTableHeightDebounce = debounce(setTableHeight, 300)

onMounted(() => {
  setTableHeight()
  window.addEventListener('resize', setTableHeightDebounce)
})

onUnmounted(() => {
  window.removeEventListener('resize', setTableHeightDebounce)
})
</script>

<style lang="css" scoped>
.container {
  padding: 5px;
  display: flex;
  flex-wrap: wrap; /* 子元素超出容器宽度时换行 */
}
</style>
